package com.thinkersre.controller;


import com.google.code.kaptcha.Producer;
import com.thinkersre.config.SecurityConfig;
import com.thinkersre.entity.User;
import com.thinkersre.service.UserService;
import com.thinkersre.util.RedisKeyUtil;
import com.thinkersre.util.ThinkersReConstant;
import com.thinkersre.util.ThinkersReUtil;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Controller
public class LoginController implements ThinkersReConstant {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Resource
    private UserService userService;
    @Resource
    private Producer kaptchaProducer;
    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Resource
    private RedisTemplate redisTemplate;

    @PostMapping("/register")
    public String register(Model model, User user){
        //注册，map接收
        Map<String,Object> map = userService.register(user);
        //根据model状态判断
        if(map.isEmpty()){
            model.addAttribute("msg","注册成功,我们已经往您的邮箱发送了激活邮件，请前往激活");
            model.addAttribute("target","/index");
            return "/site/operate-result";
        }else{
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            model.addAttribute("emailMsg",map.get("emailMsg"));
            return "/site/register";
        }

    }
    @GetMapping("/register")
    public String getRegisterPage(){

        return "/site/register";
    }
    @GetMapping("/login")
    public String getLoginPage(){

        return "/site/login";
    }

//    @ApiOperation("登陆处理功能")
    @PostMapping("/login")
    //这里的参数从html的相关输入框的代码属性name中获取
    public String login(/*@ApiParam("用户名")*/ String username,/*@ApiParam("密码")*/ String password,/*@ApiParam("验证码")*/ String code,
                        /*@ApiParam("记住我")*/boolean rememberMe,/*@ApiParam("返回响应")*/ Model model,/*@ApiParam("取出服务器生成的验证码") HttpSession httpSession,*/
                        /*@ApiParam("用于创建cookie")*/HttpServletResponse httpServletResponse,
                        /*@ApiParam("存储kaptcha的cookie")*/@CookieValue("kaptchaOwner") String kaptchaOwner){
        //检查验证码
//        String kaptcha = (String) httpSession.getAttribute("kaptcha");
        String kaptcha = null;
        if (StringUtils.isNotBlank(kaptchaOwner)){
            String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
            kaptcha = (String) redisTemplate.opsForValue().get(redisKey);

        }
//        if (StringUtils.isBlank(kaptcha))
         if (StringUtils.isBlank(code)||StringUtils.isBlank(kaptcha)||!code.equalsIgnoreCase(kaptcha)){
             model.addAttribute("codeMsg","验证码有误");
             return "/site/login";
         }
         //检查账号和密码
        int expiredSeconds = rememberMe ? REMEMBER_EXPIRED_SECONDS : DEFAULT_EXPIRED_SECONDS;
         Map<String,Object> map = userService.login(username,password,expiredSeconds);
         if (map.containsKey("ticket")){
             //存入客户端cookie，让其携带可供服务器识别的ticket
             Cookie cookie = new Cookie("ticket",map.get("ticket").toString());
             //设置路径上下文
             cookie.setPath(contextPath);
             cookie.setMaxAge(expiredSeconds);
             httpServletResponse.addCookie(cookie);

             return "redirect:/index";
         }else{
             model.addAttribute("usernameMsg",map.get("usernameMsg"));
             model.addAttribute("passwordMsg",map.get("passwordMsg"));
             return "/site/login";
         }
    }

    @GetMapping("/kaptcha")
    public void getKaptcha(HttpServletResponse httpServletResponse/*, HttpSession httpSession*/){
        //生成验证码
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);
        //存入Session
//        httpSession.setAttribute("kaptcha",text);

        //验证码的归属
        String kaptchaOwner = ThinkersReUtil.getUUID();
        Cookie cookie = new Cookie("kaptchaOwner",kaptchaOwner);
        cookie.setMaxAge(60);
        cookie.setPath(contextPath);
        httpServletResponse.addCookie(cookie);
        //将验证码存入Redis
        String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
        redisTemplate.opsForValue().set(redisKey,text,60, TimeUnit.SECONDS);


        //将图片传给浏览器
        httpServletResponse.setContentType("image/png");
        try {
            OutputStream outputStream = httpServletResponse.getOutputStream();
            ImageIO.write(image,"png",outputStream);
        } catch (IOException e) {
            logger.error("响应验证码失败:"+e.getMessage());
        }
    }

    @GetMapping("/activation/{userId}/{code}")
    public String activation(Model model, @PathVariable("userId")int userId,@PathVariable("code")String code){
        int result = userService.activation(userId,code);
        if(result == ACTIVATION_SUCCESS){
            model.addAttribute("msg","激活成功");
            model.addAttribute("target","/login");
        } else if (result == ACTIVATION_REPEAT) {
            model.addAttribute("msg","失败，重复激活");
            model.addAttribute("target","/login");
        }else{
            model.addAttribute("msg","失败，激活码有误");
            model.addAttribute("target","/index");
        }

        return "/site/operate-result";
    }

    @GetMapping("/logout")
    public String lougout(@CookieValue("ticket") String ticket){
        userService.logout(ticket);
        SecurityContextHolder.clearContext();
        return "redirect:/login";

    }



/* 以下为测试代码 */
/* 样式开始 ===============================================================================*/
//获得验证码//
    @RequestMapping(path = "/user/getCode", method = RequestMethod.POST)
    @ResponseBody
    public String getCode(String email, HttpSession httpSession, HttpServletResponse httpServletResponse) {

        if (httpSession.getAttribute("cd") != null && LocalDateTime.now().isBefore((LocalDateTime) httpSession.getAttribute("cd"))) {
            return ThinkersReUtil.getJSONString(1, "您点击的太快了,休息一分钟吧!");
        }
        Map<String, Object> map = userService.getCode(email);
        String code = null;

        if (map.containsKey("emailMsg")) {
            return ThinkersReUtil.getJSONString(1, map.get("emailMsg").toString());
        }

        if (map.containsKey("code")) {
            code = (String) map.get("code");
        }

        if (code != null) {
            httpSession.setAttribute("code", code);
            httpSession.setAttribute("expirationTime",map.get("expirationTime"));
            httpSession.setAttribute("cd",map.get("cd"));

            Cookie cookie = new Cookie("email", email);
            cookie.setMaxAge(300);
            cookie.setPath(contextPath);
            httpServletResponse.addCookie(cookie);
        }
        return ThinkersReUtil.getJSONString(0, "验证码发送成功,请注意查收!");
    }



    //跳转忘记密码页面
    @RequestMapping(path = "/forget",method = RequestMethod.GET)
    public String getForgetPage() {
        return "/site/forget";
    }


    //重置密码
    @RequestMapping(path = "/user/forget",method = RequestMethod.POST)
    public String resetPassword(String password, String email, String code, HttpSession httpSession, Model model, HttpServletRequest httpServletRequest) {
        if (email == null) {
            model.addAttribute("emailMsg", "请输入邮箱!");
            return "/site/forget";
        }
        Cookie[] cookies = httpServletRequest.getCookies();
        Cookie cookie = new Cookie("null", "null");
        for (Cookie cookie1 : cookies) {
            if (cookie1.getName().equals("email")) {
                cookie = cookie1;
                break;
            }
        }

        Map<String, Object> map = userService.resetPasswordMsg(password, code);
        if (map.isEmpty())
        {
            if (LocalDateTime.now().isAfter((LocalDateTime) httpSession.getAttribute("expirationTime"))) {
                model.addAttribute("codeMsg", "输入的验证码已过期，请重新获取验证码!");
                model.addAttribute("email", email);
                return "/site/forget";
            }
            try {
                if (httpSession.getAttribute("code").toString().equals(code)) {

                    if (!cookie.getValue().equals(email)) {
                        model.addAttribute("emailMsg", "验证码和邮箱不匹配,请重新获取验证码!");
                        return "/site/forget";
                    }

                    userService.updatePasswordByEmail(email, password);

                    httpSession.removeAttribute("code");
                    httpSession.removeAttribute("expirationTime");
                    httpSession.removeAttribute("cd");

                    cookie.setMaxAge(0);

                    model.addAttribute("msg", "密码修改成功,请重新登录!");
                    model.addAttribute("target", "/login");
                    model.addAttribute("email", email);
                    model.addAttribute("username", userService.findUserByEmail(email).getUsername());

                    return "/site/operate-result";
                } else {
                    model.addAttribute("codeMsg", "验证码错误!");
                    model.addAttribute("email", email);
                    return "/site/forget";
                }
            } catch (Exception e) {
                model.addAttribute("codeMsg", "请先获取验证码!");
                return "/site/forget";
            }

        }

        model.addAttribute("codeMsg", map.get("codeMsg"));
        model.addAttribute("passwordMsg", map.get("passwordMsg"));
        model.addAttribute("email", email);

        return "/site/forget";
    }

}
